package cn.webrx.bs.servlet;

import cn.webrx.bs.entity.Book;
import cn.webrx.bs.service.BookDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>功能描述: </p>
 *
 * @author webrx
 * @version 1.0
 * @date 2020-09-08 11:58
 */
@WebServlet("/shopbag")
public class ShopBag extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        HttpSession session = req.getSession();
        boolean flag = false;
        String a = req.getParameter("action") == null ? "show" : req.getParameter("action");
        Map<Integer, Map<String, Object>> map = new HashMap<Integer, Map<String, Object>>();
        if (session.getAttribute("shopbag") == null) {
            session.setAttribute("shopbag", map);
        }
        map = (Map<Integer, Map<String, Object>>) session.getAttribute("shopbag");
        int id = req.getParameter("id") == null ? 0 : Integer.parseInt(req.getParameter("id"));
        switch (a) {
            case "del"://删除购物车中的商品
                map.remove(id);
                break;
            case "update":
                map.get(id).put("num",Integer.parseInt(req.getParameter("num")));
                break;
            case "add"://向购物车中添加商品
                Book book = new BookDaoImpl().queryById(id);
                if (map.containsKey(id)) {
                    int num = (int) map.get(id).get("num");
                    map.get(id).put("num", ++num);
                } else {
                    Map<String, Object> mm = new HashMap<String, Object>();
                    mm.put("id", book.getId());
                    mm.put("name", book.getName());
                    mm.put("price", book.getPrice());
                    mm.put("num", 1);
                    map.put(book.getId(), mm);
                }
                flag = true;
                break;
            case "ok":
                break;
            case "delall":
                map.clear();
                break;
            default://默认查看
                break;
        }
        if(flag){
            resp.sendRedirect("/shopbag");
        }else {
            req.setAttribute("map", map);
            req.getRequestDispatcher("/home/shopbag.ftl").forward(req, resp);
        }
    }
}
